// pages/invoice/invoice.js
const app = getApp();
var modal = null;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataType:'',
    invoiceTitle:'二维码识别发票-通用电子发票',
    invoiceBg:'/images/general.png',
    modalHide:true,
    reqUrl:'',
    reqData:{},
    reqSearch:'',
    icvInfo:[],
    confirmText:'确认信息',
    layerColor:'blue',
    layerPic:'/images/smile.png',
    layerTitle:'提交成功',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '正在识别...',
    })
    console.log(options)
    modal = require('../../utils/modal/modal.js');
    this.layerClose = modal.layerClose;
    let paramArr = options.ivcParam.split(',');
    var baseUrl = app.globalData.appUrl+'/invoice/invoice_';
    this.setData({
      dataType: options.dataType,
      confirmText:'确认信息'
    })
    if (options.dataType == 'general') {
      let date = paramArr.length==7?paramArr[5].split(''):paramArr[2].split('')
      date.splice(4, 0, '-')
      date.splice(7, 0, '-')
      date=date.join('')
      let dateReq = date+' 00:00:00'
      this.setData({
        invoiceTitle: '二维码识别发票-通用电子发票',
        invoiceBg: '/images/general.png',
        reqUrl: baseUrl + 'machine/add',
        reqData:{
          "invoiceCode": paramArr.length==7?paramArr[2]:paramArr[0],
          "invoiceNumber": paramArr.length==7?paramArr[3]:paramArr[1],
          "invoiceDate": dateReq,
          "money": paramArr.length==7?paramArr[4]:paramArr[3]
        },
        reqSearch: '?invoiceCode=' + paramArr.length==7?paramArr[2]:paramArr[0] + '&invoiceNumber=' + paramArr.length==7?paramArr[3]:paramArr[1] + '&invoiceDate=' + paramArr.length==7?paramArr[5].split(''):paramArr[2] + '&money=' + paramArr.length==7?paramArr[4]:paramArr[3],
        icvInfo: [
          { name: '发票金额', value: paramArr.length==7?paramArr[4]:paramArr[3]},
          { name: '发票代码', value: paramArr.length==7?paramArr[2]:paramArr[0] },
          { name: '发票号码', value: paramArr.length==7?paramArr[3]:paramArr[1] },
          { name: '发票日期', value:date},
          { name: '验证码', value: paramArr.length==7?paramArr[6]:paramArr[4] },
        ]
      })
    } else if (options.dataType == 'plain') {
      let date = paramArr[5].split('')
      date.splice(4, 0, '-')
      date.splice(7, 0, '-')
      date = date.join('')
      let dateReq = date + ' 00:00:00'
      this.setData({
        invoiceTitle: '二维码识别发票-增值税普票',
        invoiceBg: '/images/plain.png',
        reqUrl: baseUrl + 'vat',
        reqData: {
          "lineNumber": paramArr[0],
          "invoiceType": paramArr[1],
          "invoiceCode": paramArr[2],
          "invoiceNumber": paramArr[3],
          "invoiceDate": dateReq,
          "taxFreeAmount": paramArr[4],
          "checkCode": paramArr[6]
        },
        reqSearch: '?lineNumber=' + paramArr[0] + '&invoiceType=' + paramArr[1] + '&invoiceCode=' + paramArr[2] + '&invoiceNumber=' + paramArr[3] + '&invoiceDate=' + paramArr[5] + '&money=' + paramArr[4] + '&checkCode=' + paramArr[6],
        icvInfo: [
          { name: '发票金额', value: paramArr[4] },
          { name: '发票种类代码', value: paramArr[0] },
          { name: '发票代码', value: paramArr[2] },
          { name: '发票号码', value: paramArr[3] },
          { name: '发票日期', value: date },
          { name: '校验码', value: paramArr[6] },
        ]
      })
    } else if (options.dataType == 's1vat') {
      this.specialSetdata(paramArr, '1vat')
    } else if (options.dataType == 's3vat') {
      this.specialSetdata(paramArr, '3vat')
    } else if (options.dataType == 's6vat') {
      this.specialSetdata(paramArr, '6vat')
    }
    wx.hideLoading()
    console.log(this.data.reqUrl)
  },

  specialSetdata(paramArr, searchUrl){
    var baseUrl = app.globalData.appUrl + '/invoice/invoice_';
    let date = paramArr[5].split('')
    date.splice(4, 0, '-')
    date.splice(7, 0, '-')
    date = date.join('')
    let dateReq = date + ' 00:00:00'
    this.setData({
      invoiceTitle: '二维码识别发票-增值税专票',
      invoiceBg: '/images/special.png',
      reqUrl: baseUrl + searchUrl,
      reqData: {
        "lineNumber": paramArr[0],
        "invoiceType": paramArr[1],
        "invoiceCode": paramArr[2],
        "invoiceNumber": paramArr[3],
        "invoiceDate": dateReq,
        "taxFreeAmount": paramArr[4]
        // ,"taxCode": paramArr[6]
      },
      reqSearch: '?lineNumber=' + paramArr[0] + '&invoiceType=' + paramArr[1]+ '&invoiceCode=' + paramArr[2] + '&invoiceNumber=' + paramArr[3] + '&invoiceDate=' + paramArr[5] + '&taxFreeAmount=' + paramArr[4],
      //  + '&taxCode=' + paramArr[6]
      icvInfo: [
        { name: '发票金额', value: paramArr[4] },
        { name: '发票种类代码', value: paramArr[0] },
        { name: '发票代码', value: paramArr[2] },
        { name: '发票号码', value: paramArr[3] },
        { name: '发票日期', value: date },
        // { name: '校验码', value: paramArr[6] },
      ]
    })
  },

  back(){wx.navigateBack({})},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  ivcConfirm(){
    let that=this;
    // + that.data.reqSearch
    wx.request({
      url: that.data.reqUrl,
      data: that.data.reqData,
      header: { 
        'Content-Type': 'application/json',
        //application/x-www-form-urlencode
        'Authorization': 'Bearer '+app.globalData.token 
      },
      method:'POST',
      success(e) {
        console.log(e, '提交结果')
        if (e.data.code=='00000'){
          // e.data.status==1000
          that.setData({
            layerColor:'blue',
            layerPic: '/images/smile.png',
            layerTitle: '提交成功',
            modalHide: false
          })
          setTimeout(function () {
            that.layerClose()
            that.setData({
              confirmText: '继续识别'
            })
            that.scanNext()
          }, 1800)
        }else{
          let regCN = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5|\u4e00-\u9fa5]/g
          that.setData({
            layerColor: 'red',
            layerPic: '/images/unhappy.png',
            layerTitle: e.data.message ? (e.data.message.match(regCN).join('')):((e.data.match(regCN).join('').split('！')[0]+'！')),
            modalHide: false
          })
          setTimeout(function () {
            that.layerClose()
            if (e.data.message == '发票已存在' || e.data.message == '已有该发票' || e.data.message == '该发票已存在'){
              that.setData({
                confirmText: '继续识别'
              })
              that.scanNext()
            } else if (e.data.message.indexOf('登录超时')!=-1){
              wx.reLaunch({
                url: '/pages/login/login',
              })
            }else{
              that.setData({
                confirmText: '重新提交'
              })
            }
          }, 1800)
        }
      },
      fail(e){
        console.log(e, '错误信息')
        that.setData({
          layerColor: 'red',
          layerPic: '/images/unhappy.png',
          layerTitle: '提交失败',
          modalHide: false
        })
        setTimeout(function () { 
          that.layerClose()
          that.setData({
            confirmText: '重新提交'
          })
        }, 1800)
      }
    })
  },

  scanNext(){
    let that = this, dataType = that.data.dataType;
    wx.scanCode({
      success(res){
        function reload() {
          // wx.navigateTo({
          //   url: '/pages/invoice/invoice?dataType=' + dataType + '&ivcParam=' + res.result,
          // })
          that.onLoad({ dataType: dataType, ivcParam: res.result})
        }
        if (dataType == 'general') {
          app.generalMatch(res, reload, function (message) {
            that.errLayer(message)
          })
        } else if (dataType == 'plain') {
          app.plainMatch(res, reload, function (message) {
            that.errLayer(message)
          })
        } else if (dataType == 's1vat' || dataType == 's3vat' || dataType == 's6vat') {
          app.specialMatch(res, reload, function (message) {
            that.errLayer(message)
          })
        }
      },
      fail(res) {
        wx.showToast({
          icon: 'none',
          title: '扫码未成功！',
        })
      }
    })
  },

  errLayer(msg) {
    let that = this;
    this.setData({
      modalHide: false,
      layerColor: 'red',
      layerPic: '/images/unhappy.png',
      layerTitle: msg
    })
    setTimeout(function () { that.layerClose() }, 1800)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.shareData()
  }
})